<template>
  <DialogTable
    ref="productTable"
    :refresh="tableInfo.refresh"
    :init-curpage="tableInfo.initCurpage"
    v-model:data="tableInfo.data"
    :api="tableInfo.api"
    v-model:query="filterInfo.query"
    :field-list="tableInfo.fieldList"
    :handle="tableInfo.handle"
    :rowKey="rowKey"
    :highlight-row="highlightRow"
    :checkedRowList="checkedRowList"
    :reserve-selection="true"
    :check-box="checkBox"
    :pager="pager"
    @pageInfo="pageInfo"
    @handleEvent="handleEvent"
    @dbClick="dbClick"
  >
    <template v-slot:col-storeBatchNumber="scope">
      <StoreBatchNumberTag :row="scope.row" />
    </template>
  </DialogTable>
  <div class="page-info" v-if="tableInfo.pageInfo.total">
    <span>共{{ tableInfo.pageInfo.total || 0 }}条</span>
    <span class="actionBtn" @click="checkMore">更多</span>
  </div>
</template>
<script setup name="SelectProduct">
import { getCustomizeSetting } from '@/api/customize'
import { getDepotStockCustomizeListPage } from '@/api/stock.js'
import StoreBatchNumberTag from '@/views/stock/components/StoreBatchNumberTag'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  popoVisible: {
    type: Boolean,
    default: false,
  },
  pager: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  rowKey: {
    type: String,
    default: 'id',
  },
  api: {
    type: Function,
    default: getDepotStockCustomizeListPage,
  },
  showPrice: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  tableKey: {
    type: String,
    default: '',
  },
  checkedList: {
    type: Array,
    default: () => {
      return []
    },
  },
  checkedRowList: {
    type: Array,
    default: () => {
      return []
    },
  },
  saveEmpty: {
    type: Boolean,
    default: false,
  },
  refresh: {
    type: Number,
    default: 1,
  },
  codeType: {
    type: Number,
  },
  tableType: {
    type: String,
    default: '',
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    sortString: '',
    queryMap: {},
    queryParams: {},
    excludeQueryList: [],
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  fieldList: [],
  pageInfo: {},
  index: -1,
})
const selectRow = ref([])
onMounted(() => {
  window.addEventListener('keydown', keyDown, true)
})
onUnmounted(() => {
  window.removeEventListener('keydown', keyDown, true)
})
watch(
  () => props.refresh,
  (val) => {
    filterInfo.value.query.queryMap = { ...props.query.queryMap }
    filterInfo.value.query.queryParams = { ...props.query.queryParams }
    filterInfo.value.query.excludeQueryList = props.query.excludeQueryList
    setData()
  },
  {
    immediate: true,
  }
)
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      hidden: true,
      type: 'column',
      show: false,
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !props.showPrice,
      show: false,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    showPrice: {
      label: '展示价格',
      value: 'showPrice',
      type: 'column',
      show: false,
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function keyDown(event) {
  const e = event || window.event || arguments.callee.caller.arguments[0]
  let k = e.keyCode //40下，38上，13enter
  if (!tableInfo.value.data.length) return
  if (selectRow.value && selectRow.value.id) {
    tableInfo.value.index = tableInfo.value.data.findIndex(
      (item) => item.id === selectRow.value.id
    )
  }
  if (k === 38) {
    tableInfo.value.index -= 1
    if (tableInfo.value.index <= 0) {
      emits('keyDown', tableInfo.value.index)
      tableInfo.value.index = 0
    }
    let row = tableInfo.value.data[tableInfo.value.index]
    proxy.$refs.productTable.setCurrentRow(row)
  } else if (k === 40) {
    tableInfo.value.index += 1
    if (tableInfo.value.index >= tableInfo.value.data.length - 1) {
      tableInfo.value.index = tableInfo.value.data.length - 1
    }
    let index = proxy.$fn.deepClone(tableInfo.value.index)
    let row = tableInfo.value.data[index]
    proxy.$refs.productTable.setCurrentRow(row)
    emits('keyDown')
  } else if (k === 13) {
    if (selectRow.value && selectRow.value.id) {
      save()
    }
  }
}
// 获取列表
function getList() {
  proxy.$nextTick(() => {
    tableInfo.value.refresh = Math.random()
  })
}
function search() {
  proxy.$nextTick(() => {
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  })
}
function pageInfo(obj) {
  tableInfo.value.pageInfo = obj
}
function dbClick(row) {
  if (!tableInfo.value.data.length) return
  tableInfo.value.index = tableInfo.value.data.findIndex(
    (item) => item.id === row.id
  )
  selectRow.value.depotStockIdClone = row.depotStockId
  selectRow.value.depotStockId = row.id
  emits('reset')
  emits('callback', row)
}
function save() {
  selectRow.value.depotStockIdClone = selectRow.value.depotStockId
  selectRow.value.depotStockId = selectRow.value.id
  emits('reset')
  emits('callback', selectRow.value)
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      selectRow.value = data
      break
    case 'tableCheck':
      break
  }
}
function checkMore() {
  emits('checkMore')
  emits('reset')
}
function getCustomize() {
  let param = { tableKey: props.tableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      if (props.tableType === 'batch') {
        tableInfo.value.fieldList.forEach((item) => {
          if (props.codeType === 1 || props.codeType === 4) {
            if (
              item.value === 'uniqueCode' ||
              item.value === 'factoryMainCode' ||
              item.value === 'factorySubCode'
            ) {
              item.hidden = true
            }
            if (item.value === 'qrCode') {
              item.hidden = true
            }
          } else if (props.codeType === 2) {
            if (
              item.value === 'factoryMainCode' ||
              item.value === 'factorySubCode'
            ) {
              item.hidden = true
            }
          } else if (props.codeType === 3) {
            if (item.value === 'uniqueCode') {
              item.hidden = true
            }
          }
        })
      }
      tableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'storeBatchNumber') {
          item['type'] = 'slot'
        }
      })
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      console.log(props.api)
      tableInfo.value.api = props.api
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
.page-info {
  padding-top: 10px;
  span {
    padding-left: 10px;
  }
}
:deep(.el-scrollbar__view) {
  height: 100%;
}
:deep(.el-scrollbar) {
  min-height: 290px;
}
</style>
